//
//  LGAddMedicineController.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2023/6/16.
//

#import "LGAddMedicineController.h"
//搜索药品
#import "LGSearchMedicineController.h"
#import "LGAddMedicineTimeCell.h"
#import "LGAddMedicinHeadView.h"
#import "LGCustomTextView.h"
#import "LGPickerView.h"
#define placeHolder  @"请输入..."
@interface LGAddMedicineController ()<UITableViewDelegate,UITableViewDataSource,LGTextViewDelegate>
/**   */
@property (nonatomic , strong)UITableView *tableView;
/**   */
@property (nonatomic , strong)UISwitch *stopSwitch;
/**   */
@property (nonatomic , strong)LGCustomTextView *remarkTF;
/**   */
@property (nonatomic , strong)NSArray *sectionArray;
/**  服药频率 */
@property (nonatomic , strong)NSArray *rateArray;
/**  时段 */
@property (nonatomic , strong)NSArray *timeArray;
/**  剂量 */
@property (nonatomic , strong)NSArray *doseArray;
/**   */
@property (nonatomic , strong)NSMutableDictionary *resultDic;
/**   */
@property (nonatomic , assign)CGFloat remarkHeight;
/**   */
@property (nonatomic , copy)NSString *isstop;
@end

@implementation LGAddMedicineController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.isstop = @"0";
    self.remarkHeight = viewPix(102);
    self.title = (_medicineId && _medicineId.length>0)?@"编辑用药":@"添加用药";
    self.medicineId = (_medicineId && _medicineId.length>0)?_medicineId:@"";
    self.tempPrescripid = (_tempPrescripid && _tempPrescripid.length>0)?_tempPrescripid:@"";
    self.sectionArray = @[
        @{@"title":@"药品名称",@"showTip":@"Y",@"showLine":@"N",@"key":@"name"},
        @{@"title":@"服药频率",@"showTip":@"Y",@"showLine":@"N",@"key":@"take_frequency"},
        @{@"title":@"时段、剂量",@"showTip":@"N",@"showLine":@"Y",@"key":@""},
        @{@"title":@"备注",@"showTip":@"N",@"showLine":@"N",@"key":@""},
        @{@"title":@"结束用药",@"showTip":@"N",@"showLine":@"N",@"key":@"isstop"}];
    self.timeArray = @[@{@"title":@"空腹",@"key":@"take_dose_zero"},@{@"title":@"早饭后",@"key":@"take_dose_one"},@{@"title":@"中饭后",@"key":@"take_dose_two"},@{@"title":@"晚饭后",@"key":@"take_dose_three"},@{@"title":@"睡前",@"key":@"take_dose_four"},@{@"title":@"必要时",@"key":@"take_dose_five"}];
    [self.view addSubview:self.tableView];
    [self createButtomView];
    [self requestData];
}

-(void)requestData{
    [RequestUtil withPOST:@"/doctor/Sportsprescription.MedicinePrescription/medicineDetail" parameters:@{@"temp_prescription_id":self.tempPrescripid,@"prescription_medicine_id":self.medicineId} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if(code == 200){
//            self.medicineId = LGNSString(returnData[@"prescription_medicine_id"]);
            self.isstop = [[returnData allKeys] containsObject:@"isstop"]?LGNSString(returnData[@"isstop"]):@"0";
            self.stopSwitch.on = [self.isstop isEqualToString:@"1"]?YES:NO;
            self.remarkTF.content = LGNSString(returnData[@"remark"]);
            self.resultDic = [NSMutableDictionary dictionaryWithDictionary:returnData];
            [self.resultDic removeObjectForKey:@"take_dose_select"];
            [self.resultDic removeObjectForKey:@"take_frequency_select"];
            NSMutableArray *doseArray = [NSMutableArray array];
            NSMutableArray *rateArray = [NSMutableArray array];
            NSArray *takeDose = returnData[@"take_dose_select"];
            NSArray *takeRate = returnData[@"take_frequency_select"];
            for (NSInteger i=0; i<takeDose.count; i++) {
                [doseArray addObject:LGNSString(takeDose[i][@"title"])];
            }
            
            for (NSInteger i=0; i<takeRate.count; i++) {
                [rateArray addObject:LGNSString(takeRate[i][@"title"])];
            }
            self.doseArray = doseArray;
            self.rateArray = rateArray;
            [self.tableView reloadData];
        }
    } error:^(NSError *error) {
        
    }];
}

//药品名称
-(void)selectMedicineName{
    LGSearchMedicineController *controller = [[LGSearchMedicineController alloc]init];
    controller.tempPrescripid = self.tempPrescripid;
    controller.patientid = self.patientid;
    controller.canSelect = YES;
    [self.navigationController pushViewController:controller animated:YES];
    __weak typeof(self) weakSelf = self;
    controller.selectMedicineResult = ^(NSDictionary * _Nonnull dataDic) {
        [weakSelf.resultDic setValue:LGNSString(dataDic[@"medicine_id"]) forKey:@"medicine_id"];
        [weakSelf.resultDic setValue:LGNSString(dataDic[@"unit"]) forKey:@"unit"];
        [weakSelf.resultDic setValue:LGNSString(dataDic[@"name"]) forKey:@"name"];
        [weakSelf.tableView reloadData];
    };
}

//服药频率
-(void)selectMedicineRate{
    if(self.rateArray.count>0){
        LGPickerView *pickerView = [[LGPickerView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H)];
        pickerView.titleLabel.text = @"服药频率";
        pickerView.pickArry = @[self.rateArray];
        pickerView.selectStr = (LGNSString(self.resultDic[@"take_frequency"]).length>0)?LGNSString(self.resultDic[@"take_frequency"]):LGNSString(self.rateArray[0]);
        [self.view.window addSubview:pickerView];
        __weak typeof(self) weakSelf = self;
        pickerView.selectPickViewResult = ^(NSArray *resultArray) {
            [weakSelf.resultDic setValue:LGNSString(resultArray[0]) forKey:@"take_frequency"];
            [weakSelf.tableView reloadData];
        };
    }else{
        [self requestData];
    }
}

-(void)stopStatusChanged:(UISwitch *)sender{
    self.isstop = (sender.on == YES)?@"1":@"0";
}

//保存
-(void)saveMedicineAction{
    NSString *name = LGNSString(self.resultDic[@"name"]);
    NSString *frequency = LGNSString(self.resultDic[@"take_frequency"]);
    NSString *take_zero = LGNSString(self.resultDic[@"take_dose_zero"]);
    NSString *take_one = LGNSString(self.resultDic[@"take_dose_one"]);
    NSString *take_two = LGNSString(self.resultDic[@"take_dose_two"]);
    NSString *take_three = LGNSString(self.resultDic[@"take_dose_three"]);
    NSString *take_four = LGNSString(self.resultDic[@"take_dose_four"]);
    NSString *take_five = LGNSString(self.resultDic[@"take_dose_five"]);
    
    if(name.length == 0){
        [TooltipView showMessage:@"请选择服用药物" offset:0];
        return;
    }
    
    if(frequency.length == 0){
        [TooltipView showMessage:@"请选择服药频率" offset:0];
        return;
    }
    
    if(take_one.length == 0 && take_two.length == 0 && take_three.length == 0 && take_four.length == 0 && take_zero.length == 0 && take_five.length == 0){
        [TooltipView showMessage:@"请选择服药时段、剂量" offset:0];
        return;
    }

    NSMutableDictionary *tempDic = [NSMutableDictionary dictionaryWithDictionary:self.resultDic];
    [tempDic setValue:self.tempPrescripid forKey:@"temp_prescription_id"];
    [tempDic setValue:self.patientid forKey:@"patient_id"];
    [tempDic setValue:self.isstop forKey:@"isstop"];
    
    [RequestUtil withPOST:@"/doctor/Sportsprescription.MedicinePrescription/medicineSave" parameters:tempDic withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if(code == 200){
            [TooltipView showMessage:@"保存成功" offset:0];
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [TooltipView showMessage:message offset:0];
        }
    } error:^(NSError *error) {
        [TooltipView showMessage:LGErrorMessage offset:0];
    }];
}

//删除
-(void)delegateMedicienAction{
    __weak typeof(self) weakSelf = self;
    [LGAlertTool alertWithTitle:@"确认删除这条药物吗？" sureAction:^{
        [RequestUtil withPOST:@"/doctor/Sportsprescription.MedicinePrescription/medicineDelete" parameters:@{@"prescription_medicine_id":weakSelf.medicineId} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
            if(code == 200){
                [TooltipView showMessage:@"删除成功" offset:0];
                [weakSelf.navigationController popViewControllerAnimated:YES];
            }else{
                [TooltipView showMessage:message offset:0];
            }
        } error:^(NSError *error) {
            [TooltipView showMessage:LGErrorMessage offset:0];
        }];
    }];
}


-(void)textViewValueChanged:(NSString *)content{
    [self.resultDic setValue:content forKey:@"remark"];
}

-(void)textViewHeightChanged:(CGFloat)height{
    if(height != self.remarkHeight  && height>=viewPix(102)){
        self.remarkHeight = height;
        self.remarkTF.frame = CGRectMake(viewPix(28), viewPix(5), Screen_W-viewPix(56), height);
        [self.tableView reloadData];
    }
}

#pragma mark
#pragma mark ====> 创建控件
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 5;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return (section == 2)?self.timeArray.count:0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LGAddMedicineTimeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.dataDic = self.timeArray[indexPath.row];
    cell.resultDic = self.resultDic;
    __weak typeof(self) weakSelf = self;
    cell.clearSelectResult = ^(NSString * _Nonnull key) {
        [weakSelf.resultDic setValue:@"" forKey:key];
        [weakSelf.tableView reloadData];
    };
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    __block NSString *key = LGNSString(self.timeArray[indexPath.row][@"key"]);
    LGPickerView *pickerView = [[LGPickerView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H)];
    pickerView.titleLabel.text = @"选择剂量";
    pickerView.pickArry = @[self.doseArray];
    pickerView.selectStr = (LGNSString(self.resultDic[key]).length>0)?LGNSString(self.resultDic[key]):@"1";
    [[ObjectTool mainWindow] addSubview:pickerView];
    __weak typeof(self) weakSelf = self;
    pickerView.selectPickViewResult = ^(NSArray *resultArray) {
        NSString *content = LGNSString(resultArray[0]);
        [weakSelf.resultDic setValue:content forKey:key];
        [weakSelf.tableView reloadData];
    };
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return (section<2)?viewPix(70):viewPix(52);
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    CGFloat height = (section<2)?viewPix(70):viewPix(52);
    LGAddMedicinHeadView *headView = [[LGAddMedicinHeadView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, height)];
    headView.dataDic = self.sectionArray[section];
    headView.resultDic = self.resultDic;
    if(section == 0){
        [headView.actionBtn addTarget:self action:@selector(selectMedicineName) forControlEvents:UIControlEventTouchUpInside];
    }else if (section == 1){
        [headView.actionBtn addTarget:self action:@selector(selectMedicineRate) forControlEvents:UIControlEventTouchUpInside];
    }else if (section == 4){
        headView.actionBtn.hidden = YES;
        [headView.baseView addSubview:self.stopSwitch];
        [self.stopSwitch mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(headView.baseView).offset(-viewPix(10));
            make.centerY.equalTo(headView.iconView);
            make.width.equalTo(@(60));
            make.height.equalTo(@(40));
        }];
    }
    return headView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if(section<2){
        return 0.01;
    }else if (section == 2 || section == 4){
        return viewPix(15);
    }else{
        return self.remarkHeight+viewPix(20);
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    CGFloat height = 0.01;
    if (section == 2 || section == 4){
        height =  viewPix(15);
    }else if (section == 3){
        height =  self.remarkHeight+viewPix(20);
    }else{
        height =  0.01;
    }
    LGCornerFooterView *footView = [[LGCornerFooterView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, height)];
    footView.bottomMargin = viewPix(8);
    if(section == 3){
        [footView addSubview:self.remarkTF];
    }
    return footView;
}

-(UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H-topBarHeight-viewPix(70)-bottomSafeBarHeight/4.0) style:UITableViewStyleGrouped];
        [_tableView registerClass:[LGAddMedicineTimeCell class] forCellReuseIdentifier:@"cell"];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(8))];
    }
    return _tableView;
}

-(UISwitch *)stopSwitch{
    if(!_stopSwitch){
        _stopSwitch = [[UISwitch alloc]initWithFrame:CGRectMake(0, 0, 80, 40)];
        _stopSwitch.backgroundColor = [UIColor whiteColor];
        _stopSwitch.tintColor = [UIColor whiteColor];
        _stopSwitch.onTintColor = [UIColor colorWithString:kThemeColor];
        [_stopSwitch addTarget:self action:@selector(stopStatusChanged:) forControlEvents:UIControlEventValueChanged];
    }
    return _stopSwitch;
}

-(LGCustomTextView *)remarkTF{
    if(!_remarkTF){
        _remarkTF = [LGCustomTextView textViewWithPlaceHolder:@"请输入..." textColor:@"#606266" textFont:LGFont(16) textAlignment:NSTextAlignmentLeft keyboard:UIKeyboardTypeDefault];
        _remarkTF.frame = CGRectMake(viewPix(28), viewPix(5), Screen_W-viewPix(56), viewPix(102));
        _remarkTF.contentInset = UIEdgeInsetsMake(viewPix(12), viewPix(12), viewPix(12), viewPix(12));
        _remarkTF.backgroundColor = [UIColor colorWithString:@"#F5F6FA"];
        _remarkTF.cornerRidus = 8;
        _remarkTF.customDelegate = self;
    }
    return _remarkTF;
}

-(void)createButtomView{
    UIView *bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, kMaxY(self.tableView.frame), Screen_W, Screen_H-kMaxY(self.tableView.frame)-topBarHeight)];
    bottomView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bottomView];
    UIButton *saveButton = [UIButton buttonWithTitle:@"保存" titleFont:LGFontWeight(18, UIFontWeightMedium) normalColor:@"#FFFFFF" selectColor:@"#FFFFFF"];
    saveButton.frame = CGRectMake(viewPix(16), viewPix(8), Screen_W-viewPix(32), viewPix(48));
    saveButton.backgroundColor = [UIColor colorWithString:kThemeColor];
    saveButton.cornerRidus = 10;
    [saveButton addTarget:self action:@selector(saveMedicineAction) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:saveButton];
    if(_medicineId && _medicineId.length>0){
        UIButton *deleteBtn = [UIButton buttonWithTitle:@"删除" titleFont:LGFontWeight(16, UIFontWeightSemibold) textColor:@"#DD3030" imageName:@""];
        deleteBtn.frame = CGRectMake(Screen_W/2.0 - viewPix(10) - (Screen_W-viewPix(95))/2.0, viewPix(8), (Screen_W-viewPix(95))/2.0, viewPix(48));
        deleteBtn.layer.borderColor = [UIColor colorWithString:@"#DD3030"].CGColor;
        deleteBtn.layer.borderWidth = 1;
        deleteBtn.cornerRidus = 10;
        [deleteBtn addTarget:self action:@selector(delegateMedicienAction) forControlEvents:UIControlEventTouchUpInside];
        [bottomView addSubview:deleteBtn];
        saveButton.frame = CGRectMake(Screen_W/2.0+viewPix(10), viewPix(8), (Screen_W-viewPix(95))/2.0, viewPix(48));
    }
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
